# Copyright 2009 mwta committers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

# This code simply loads a saved copy of the mobile search page into amara
# and generates a textual output, rather than an automated test.
import re
import amara

doc = amara.parse(open("mobile-homepage.xhtml"))

def getHrefFromXML(doc, search_regex):
  """Returns the href link if the in search_regex is found in any <div> tags.
   
  Assumes the links are in the html body's div tags.
   
  Args:
    doc: an amara xml object
    search_regex: the regular expression to match in the href text
   
  Returns:
    the href as a string if the pattern is found, else None.
  """
  ru1 = re.compile(search_regex)
  for item in doc.html.body.div:
    try:
      # print str(item.a.xml_children[0])
      # print type(item.a.xml_children[0])
      p = ru1.search(item.a.xml_children[0])
      if p:
        return item.a.href
    except:
      pass

  return None

if __name__ == "__main__":  
  print "should return: 'u/gmm?source=m&dc=mobile-promotion'"
  print getHrefFromXML(doc, "Google Maps")  
